"""manipulate exists jobs"""

from tjob.handler.cloud_handler import CloudHandler
from tjob.initialize.setup_envs_cloud import get_cloud_default_conf
from .base_command import BaseCommand
from cleo.helpers import option, argument
from tjob.meta import JobManger, SUCCESS, FAILED, PART_SUCCESS
import re


def handle_jobs(cmd, names, is_reg, mode):
    # NOTE: mode shoud return exec flag
    return_code = None
    for name in names:
        if not is_reg:
            if getattr(JobManger(), mode)(name):
                _msg = f"{mode} [{name}] in JobManger"
                return_code = 0
            else:
                _msg = f"failed to {mode} [{name}] in JobManger"
                return_code = 1
            cmd.blue_text(_msg)
        else:
            # cmd.green_text(f"use regexp to {mode}")
            all_success = True
            all_failed = True
            for exists_name in JobManger().names:
                if re.search(name, exists_name):
                    if getattr(JobManger(), mode)(exists_name):
                        _msg = f"{mode} [{exists_name}] in JobManger"
                        all_failed = False
                    else:
                        _msg = f"failed to {mode} [{exists_name}] in JobManger"
                        all_success = False

                    cmd.blue_text(_msg)
            if all_success:
                return_code = SUCCESS
            elif all_failed:
                return_code = FAILED
            else:
                return_code = PART_SUCCESS
    # cmd.green_text(f"{mode} Done :)")
    return return_code


class JobCommand(BaseCommand):
    def handle(self) -> int:
        names = self.argument("names")
        is_reg = self.option("regexp")
        mode = self.__class__.__name__.split("Command")[0].lower()
        ret_code = handle_jobs(self, names, is_reg, mode)
        return ret_code


class StopCommand(JobCommand):
    name = "stop"
    description = "stop job in JobManager"
    arguments = [
        argument("names", optional=False, multiple=True, description="stop which jobs")
    ]

    options = [
        option(
            "regexp",
            "-k",
            description="use reg exp to remove jobs",
            flag=True,
        ),
        option(
            "platform",
            "-p",
            description="select default platform. [pai/local/cloud]",
            flag=False,
            default=None,
        ),
        option(
            "cloud_cluster",
            description="select cloud cluster. [job-k8s-cluster/job-k8s-cluster-sscz]",
            flag=False,
            default=None,
        ),
    ]

    def handle(self) -> int:
        platform = self.option("platform")
        if platform == "cloud":
            names = self.argument("names")
            cloud_handler = CloudHandler()
            cloud_cluster = self.option("cloud_cluster")
            if not cloud_cluster:
                conf = get_cloud_default_conf()
                cloud_cluster = conf["cloudCluster"]
            for name in names:
                cloud_handler.stop(name, cloud_cluster)
                self.blue_text(f"stop job {name} done")
            return

        # pai and local use JobManger to stop
        return super().handle()


class PopCommand(JobCommand):
    name = "pop"
    description = "pop job in JobManager. Wont effect PAI"
    arguments = [
        argument("names", optional=False, multiple=True, description="pop which jobs")
    ]

    options = [
        option(
            "regexp",
            "-k",
            description="use reg exp to remove jobs",
            flag=True,
        ),
    ]


class RemoveCommand(JobCommand):
    name = "remove"
    description = "remove job in JobManager"
    arguments = [
        argument(
            "names", optional=False, multiple=True, description="remove which jobs"
        )
    ]

    options = [
        option(
            "regexp",
            "-k",
            description="use reg exp to remove jobs",
            flag=True,
        ),
    ]


class RestartCommand(JobCommand):
    name = "restart"
    description = "restart job in JobManager. It will stop and clone job"
    arguments = [
        argument(
            "names", optional=False, multiple=True, description="remove which jobs"
        )
    ]
    options = [
        option(
            "regexp",
            "-k",
            description="use reg exp to remove jobs",
            flag=True,
        ),
    ]
